package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //缓存穿透
//        Shop shop = queryWithPassThrough(id);
//        cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //击穿 互斥锁
        Shop shop = queryWithMutex(id);
        if(shop == null){
            return Result.fail("商家不存在");
        }

        return Result.ok(shop);
    }

//防击穿 互斥锁
    private Shop queryWithMutex(Long id) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String key = CACHE_SHOP_KEY + id;
        //1.从redis中查询key
        String shopJson = ops.get(key);

        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //3.存在直接返回
            return JSONUtil.toBean(shopJson,Shop.class);
        }

        //是空串（注意空串和空值区别）返回
        if(shopJson != null){
            return null;
        }

        //4.缓存重建
        //4.1 锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //4.2判断是否拿到
            if (!isLock){
                //4.3失败，休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //4.4成功则查询数据库
            shop = getById(id);

            //重建延迟测试
            //Thread.sleep(200);

            //5.不存在，返回
            if(shop == null){
                //空值写入
                ops.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                //返回
                return null;
            }
            //6存在，写入redis
            ops.set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.0释放互斥锁
            unLock(lockKey);
        }
        //7.返回
        return shop;
    }
//防穿透代码
//region
    //缓存穿透代码
//    public Shop queryWithPassThrough(Long id){
//        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//        String key = CACHE_SHOP_KEY + id;
//        //1.从redis中查询key
//        String shopJson = ops.get(key);
//
//        //2.判断是否存在
//        if(StrUtil.isNotBlank(shopJson)){
//        //3.存在直接返回
//            return JSONUtil.toBean(shopJson,Shop.class);
//        }
//
//        //是空串（注意空串和空值区别）返回
//        if(shopJson != null){
//            return null;
//        }
//        //4.4成功则查询数据库
//        Shop shop = getById(id);
//        //5.不存咋，返回
//        if(shop == null){
//            //空值写入
//            ops.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
//            //返回
//            return null;
//        }
//        //6存在，写入redis
//        ops.set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);
//        //7.返回
//        return shop;
//    }
// endregion

    private boolean tryLock(String key){
        Boolean b = stringRedisTemplate
                .opsForValue()
                .setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);

    }
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
